<!-- filename: frontend/src/pages/messages/messages.vue -->
<template>
  <view class="page-container">
    <Header @open-auth-modal="isAuthModalVisible = true" />
    <AuthModal v-if="isAuthModalVisible" @close="isAuthModalVisible = false" />

    <view class="content-wrapper">
      <view class="page-header">
        <h1 class="page-title">我的私信</h1>
      </view>

      <view v-if="isLoading" class="loading-state">正在加载...</view>
      <view v-else-if="!authStore.isLoggedIn" class="login-prompt">
        <p>请先登录以查看您的私信</p>
        <button class="prompt-btn" @click="isAuthModalVisible = true">登录 / 注册</button>
      </view>
      <view v-else-if="conversations.length === 0" class="empty-state">
        <p>还没有任何私信</p>
        <p class="tip">去别人的主页开启一段对话吧</p>
      </view>

      <view v-else class="conversations-list">
        <view 
          v-for="conv in conversations" 
          :key="conv.conversation_id" 
          class="conversation-item" 
          @click="navigateToConversation(conv)"
        >
          <view class="avatar-wrapper">
            <image :src="conv.other_avatar_url || '/static/avatars/default.png'" class="avatar-image" mode="aspectFill" />
            <view v-if="conv.unread_count > 0" class="unread-badge">{{ conv.unread_count }}</view>
          </view>
          <view class="conv-main">
            <view class="conv-header">
              <text class="username">{{ conv.other_username }}</text>
              <text class="timestamp">{{ conv.last_message_at }}</text>
            </view>
            <view class="last-message">
              {{ conv.last_message_content || '...' }}
            </view>
          </view>
        </view>
      </view>
    </view>
  </view>
</template>


<script setup>
import { ref } from 'vue';
import { onShow } from '@dcloudio/uni-app';
import { useAuthStore } from '@/store/auth';
import { request } from "@/utils/request"; // 【核心修改1】

import Header from '@/components/Header/Header.vue';
import AuthModal from '@/components/AuthModal/AuthModal.vue';

const authStore = useAuthStore();
const isAuthModalVisible = ref(false);

const conversations = ref([]);
const isLoading = ref(true);

// --- 【核心修改2】重写 fetchConversations ---
const fetchConversations = async () => {
  if (!authStore.isLoggedIn) {
    isLoading.value = false;
    conversations.value = [];
    return;
  }
  isLoading.value = true;
  try {
    const data = await request({
      url: `/api/conversations`,
      method: 'GET'
    });
    if (Array.isArray(data)) {
      conversations.value = data;
    }
  } catch (error) {
    console.error("Failed to fetch conversations:", error);
    // 即使请求失败（例如 token 过期被拦截），也清空列表
    conversations.value = [];
  } finally {
    isLoading.value = false;
  }
};

// --- 无需修改的函数 ---
const navigateToConversation = (conversation) => {
  uni.navigateTo({
    url: `/pages/conversation/conversation?id=${conversation.other_user_id}&username=${conversation.other_username}`
  });
};

onShow(() => {
  fetchConversations();
});
</script>

<style scoped lang="scss">
.page-container {
  background-color: #fff;
  min-height: 100vh;
}
.content-wrapper {
  padding-top: 60px; /* Header 高度 */
  max-width: 800px;
  margin: 0 auto;
}
.page-header {
  padding: 20px;
  border-bottom: 1px solid #f0f0f0;
}
.page-title {
  font-size: 24px;
  font-weight: bold;
}
.loading-state, .empty-state, .login-prompt {
  text-align: center;
  padding: 80px 20px;
  color: #888;
}
.empty-state .tip {
  font-size: 14px;
  color: #aaa;
  margin-top: 10px;
}
.login-prompt .prompt-btn {
  margin-top: 20px;
  background-color: #007aff;
  color: white;
}

.conversations-list {
  padding: 0 10px;
}
.conversation-item {
  display: flex;
  align-items: center;
  padding: 15px 10px;
  border-bottom: 1px solid #f5f5f5;
  cursor: pointer;
  &:hover {
    background-color: #f9f9f9;
  }
}
.avatar-wrapper {
  position: relative;
  margin-right: 15px;
}
.avatar-image {
  width: 50px;
  height: 50px;
  border-radius: 50%;
}
.unread-badge {
  position: absolute;
  top: -2px;
  right: -2px;
  background-color: #e5245e;
  color: white;
  min-width: 20px;
  height: 20px;
  border-radius: 10px;
  font-size: 12px;
  display: flex;
  align-items: center;
  justify-content: center;
  padding: 0 6px;
  border: 2px solid white;
}

.conv-main {
  flex: 1;
  min-width: 0;
}
.conv-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 5px;
}
.username {
  font-size: 16px;
  font-weight: 500;
}
.timestamp {
  font-size: 12px;
  color: #aaa;
}
.last-message {
  font-size: 14px;
  color: #888;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}
</style>